/*
 * @FilePath: main.c
 * @Author: lizhi
 * @Date: 2025-04-27 11:23:12
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-04-27 11:53:04
 * Copyright: 2025 xxxTech CO.,LTD. All Rights Reserved.
 * @Descripttion:
 */
/**
 * *********************************************
 *
 * 8051 blink demo
 *
 * PIN: P11
 *
 * *********************************************
 */

#include "REG52.H"

typedef unsigned char uint8_t;
typedef unsigned int uint16_t;
typedef unsigned long uint32_t;

typedef signed char int8_t;
typedef signed int int16_t;
typedef signed long int32_t;

#define EXT0_VECTOR  0 /* 0x03 external interrupt 0 */
#define TIM0_VECTOR  1 /* 0x0b timer 0 */
#define EXT1_VECTOR  2 /* 0x13 external interrupt 1 */
#define TIM1_VECTOR  3 /* 0x1b timer 1 */
#define UART0_VECTOR 4 /* 0x23 serial port 0 */
unsigned char code LedChar[] = {
 0xC0, 0xF9, 0xA4, 0xB0, 0x99, 0x92, 0x82, 0xF8,
 0x80, 0x90, 0x88, 0x83, 0xC6, 0xA1, 0x86, 0x8E
};
// LED pin define
sbit LED0        = P3 ^ 0;
sbit LED1        = P3 ^ 1;
sbit KEY1        = P1 ^ 0;
uint8_t KeyState = 1; // Key state variable
uint8_t backup   = 1; // Backup variable
void delay_ms(uint16_t ms)
{
    uint16_t i, j;
    for (i = 0; i < ms; i++) {
        for (j = 0; j < 120; j++);
    }
}
void main()
{
    TMOD |= 0x01;              // Timer 0 mode 1 (16-bit timer)
    TH0 = (65536 - 2000) >> 8; // Set initial value
    TL0 = (65536 - 2000);
    TR0 = 1; // Start Timer 0
    EA  = 1;
    ET0 = 1; // Enable Timer 0 interrupt
    while (1) {
        if (KeyState != backup) { // Key pressed
            if (backup == 1) {
                
                P0 = LedChar
                LED0 = ~LED0; // Toggle LED
            } else {
                LED1 = ~LED1; // Turn off LED
            }
            backup = KeyState; // Update backup variable
        }
        // if (KEY1 == 0) {
        //     delay_ms(10); // Debounce delay
        //     if (KEY1 == 0) {
        //         LED0 = ~LED0;      // Toggle LED
        //         //while (KEY1 == 0); // Wait for key release
        //     }
        // }
        // TODO
    }
}

void TIM0_Handler() interrupt TIM0_VECTOR
{
    static uint8_t Keytemp = 0;                   // 00000XYZ
    TH0                    = (65536 - 2000) >> 8; // Reload timer value
    TL0                    = (65536 - 2000);
    Keytemp                = (Keytemp << 1) | KEY1; // Shift in the key state
    if (Keytemp == 0x00) {
        KeyState = 0; // Key pressed
    } else if (Keytemp == 0xFF) {
        KeyState = 1; // Key released
    }
}
